<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>js块级作用域的坑 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="这是由一道最近的面试题引发的思考。。。。。今天我想总结一下我这里遇到的坑。 ** 话不多说直接上代码 ** 12345678var a &#x3D; 0;if(true)&amp;#123;    a &#x3D; 1;    function a()&amp;#123;&amp;#125;;    a &#x3D;21;    console.log(a) &#x2F;&#x2F;21&amp;#125;console.log(a) &#x2F;&#x2F;1">
<meta property="og:type" content="article">
<meta property="og:title" content="js块级作用域的坑">
<meta property="og:url" content="http://yoursite.com/2020/06/24/js%E5%9D%97%E7%BA%A7%E4%BD%9C%E7%94%A8%E5%9F%9F%E7%9A%84%E5%9D%91/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="这是由一道最近的面试题引发的思考。。。。。今天我想总结一下我这里遇到的坑。 ** 话不多说直接上代码 ** 12345678var a &#x3D; 0;if(true)&amp;#123;    a &#x3D; 1;    function a()&amp;#123;&amp;#125;;    a &#x3D;21;    console.log(a) &#x2F;&#x2F;21&amp;#125;console.log(a) &#x2F;&#x2F;1">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-06-24T11:22:18.000Z">
<meta property="article:modified_time" content="2020-07-30T13:04:01.649Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  
<link rel="stylesheet" href="/css/style.css">

<meta name="generator" content="Hexo 5.0.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-js块级作用域的坑" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2020/06/24/js%E5%9D%97%E7%BA%A7%E4%BD%9C%E7%94%A8%E5%9F%9F%E7%9A%84%E5%9D%91/" class="article-date">
  <time datetime="2020-06-24T11:22:18.000Z" itemprop="datePublished">2020-06-24</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      js块级作用域的坑
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p> 这是由一道最近的面试题引发的思考。。。。。今天我想总结一下我这里遇到的坑。<br> ** 话不多说直接上代码 **<br> <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">if</span>(<span class="literal">true</span>)&#123;</span><br><span class="line">    a = <span class="number">1</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">a</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">    a =<span class="number">21</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(a) <span class="comment">//21</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(a) <span class="comment">//1</span></span><br></pre></td></tr></table></figure><br> <a id="more"></a></p>
<p> 这道题第一次我没有做对，看了许多博客，论坛最后知道了。。。。其内部产生了块级作用域，但是它是又如何产生的呢？</p>
<h4 id="变态的变量提升机制"><a href="#变态的变量提升机制" class="headerlink" title="变态的变量提升机制"></a>变态的变量提升机制</h4><p>关于变量提升就是在当前上下文执行之前，会把var/function声明或者定义，带var的只声明，带function的声明+定义<br>如果遇到了{}新老浏览器表现不一致（兼容ES3，兼容ES6）</p>
<ul>
<li><h6 id="IE浏览器-lt-IE10"><a href="#IE浏览器-lt-IE10" class="headerlink" title="IE浏览器&lt;=IE10"></a>IE浏览器&lt;=IE10</h6>不管{},还是一如既往的function声明+定义，而且也不会存在块级作用域。这也就是说上面js  变量a 之前都是全局的，a由0变为1，21 </li>
<li><h6 id="新版本浏览器"><a href="#新版本浏览器" class="headerlink" title="新版本浏览器"></a>新版本浏览器</h6>{}中的function，在全局只声明不定义，{}中出现function/let/const会创建一个块级上下文 <h5 id="开始描述上面执行过程"><a href="#开始描述上面执行过程" class="headerlink" title="开始描述上面执行过程"></a>开始描述上面执行过程</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//代码执行之前 创建Vo(G)对象,</span></span><br><span class="line"><span class="comment">//变量提升: var a; function a；(因为出现在&#123;&#125;中，只是声明)</span></span><br><span class="line">  <span class="keyword">var</span> a = <span class="number">0</span>; <span class="comment">//代码开 始执行 a = 0</span></span><br><span class="line">  <span class="keyword">if</span>(<span class="literal">true</span>)&#123;  <span class="comment">// &#123;&#125;发现funtion 形成块级上下文</span></span><br><span class="line"><span class="comment">// 变量提升 function a()&#123;&#125;</span></span><br><span class="line">      a = <span class="number">1</span>;  <span class="comment">//全局 a = 1</span></span><br><span class="line">      <span class="function"><span class="keyword">function</span> <span class="title">a</span>(<span class="params"></span>)</span>&#123;&#125;;  <span class="comment">// 为了兼容es3，运行到这，会把代码之前所有对a的操作映射给全局一份，后面的则不会,认为后面都是私有的</span></span><br><span class="line">      a =<span class="number">21</span>;</span><br><span class="line">      <span class="built_in">console</span>.log(a) <span class="comment">//21</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(a) <span class="comment">//1</span></span><br></pre></td></tr></table></figure>
上面代码可以用debugger以下，效果是一样的。。。<h4 id="块级作用域与函数作用域的结合"><a href="#块级作用域与函数作用域的结合" class="headerlink" title="块级作用域与函数作用域的结合"></a>块级作用域与函数作用域的结合</h4>话不多说直接上代码<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">var</span> x = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">func</span>(<span class="params">x, y = function annoymous() x = <span class="number">2</span></span>)</span>&#123;</span><br><span class="line">      <span class="comment">// 形参赋值的变量都是私有变量 x，y</span></span><br><span class="line">        x = <span class="number">3</span>;</span><br><span class="line">        y(); <span class="comment">// 没有形参赋值 x 不是自己私有变量 x为上级作用域的x</span></span><br><span class="line">        <span class="built_in">console</span>.log(x)   <span class="comment">//2</span></span><br><span class="line">    &#125;</span><br><span class="line">    func(<span class="number">5</span>); <span class="comment">// func 执行 形成 func的私有上下文 Ao</span></span><br><span class="line">    <span class="built_in">console</span>.log(x) <span class="comment">//1</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
根据上诉过程很快可以得出: 2 1,那么再来看一段代码<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">func</span>(<span class="params">x, y = function annoymous() x = <span class="number">2</span></span>)</span>&#123;</span><br><span class="line">       <span class="keyword">var</span>  x = <span class="number">3</span>;</span><br><span class="line">        y();</span><br><span class="line">        <span class="built_in">console</span>.log(x)   </span><br><span class="line">    &#125;</span><br><span class="line">    func(<span class="number">5</span>);  </span><br><span class="line">    <span class="built_in">console</span>.log(x);</span><br></pre></td></tr></table></figure>
上面介绍了es6中存在块级作用域(只要{}[ 处对象外之外 ]出现let/const/function)<br>有一种情况也会产生</li>
<li>函数有形参赋值了默认值   </li>
<li>函数体中单独声明了某个变量</li>
</ul>
<p>这样在函数运行的时候，会产生两个上下文<br> &ensp;&ensp;&ensp;第一个：函数执行形成的私有上下文EC（FUNC） =&gt; 作用域链/形参赋值<br> &ensp;&ensp;&ensp;第一个：函数大括号包起来是一个快级上下文 EC（block）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">func</span>(<span class="params">x, y = function annoymous() x = <span class="number">2</span></span>)</span>&#123;</span><br><span class="line">     <span class="comment">/*</span></span><br><span class="line"><span class="comment">      * EC（FUNC）私有上下文</span></span><br><span class="line"><span class="comment">      *   作用域链：&lt;EC（FUNC），EC(G)&gt;   </span></span><br><span class="line"><span class="comment">      *   x = 5    2</span></span><br><span class="line"><span class="comment">      *   y = annoymous  [[scope]]:EC(FUNC)</span></span><br><span class="line"><span class="comment">      *  EC(block)块级上下文 （上级上下文 EC(FUNC)）</span></span><br><span class="line"><span class="comment">      *     变量提升：var x; 3</span></span><br><span class="line"><span class="comment">      *    在代码没有执行官之前，会把EC（FUNC）给block 的x 一份</span></span><br><span class="line"><span class="comment">      */</span></span><br><span class="line">     </span><br><span class="line">     <span class="keyword">var</span>  x = <span class="number">3</span>;<span class="comment">// 块级上下文的 x =3</span></span><br><span class="line">        y();  <span class="comment">// 不是块级的 y;向上级上下文找,EC(FUNC) annoymous()执行</span></span><br><span class="line">        <span class="comment">//  形成它的私有上下文  x = 2 修改的EC（FUNC）中的2</span></span><br><span class="line">        <span class="built_in">console</span>.log(x)   <span class="comment">//3</span></span><br><span class="line">    &#125;</span><br><span class="line">    func(<span class="number">5</span>);  </span><br><span class="line">    <span class="built_in">console</span>.log(x);  <span class="comment">//1</span></span><br></pre></td></tr></table></figure>
<p>  了解了他感觉js水平又上升了一个台阶</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2020/06/24/js%E5%9D%97%E7%BA%A7%E4%BD%9C%E7%94%A8%E5%9F%9F%E7%9A%84%E5%9D%91/" data-id="ckd8udtby000g9gt4b6djg2ig" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/js/" rel="tag">js</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2020/06/28/%E7%BB%84%E4%BB%B6_%E5%A4%84%E7%90%86%E8%BE%B9%E7%95%8C%E6%83%85%E5%86%B5/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          组件_处理边界情况
        
      </div>
    </a>
  
  
    <a href="/2020/06/22/Vue%E4%B8%ADV-model%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86%E5%8F%8A%E5%A6%82%E4%BD%95%E5%AE%9A%E4%B9%89V-model/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">V-model的实现原理及如何定义V-model</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Vue/" rel="tag">Vue</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Vue%E5%85%A8%E5%AE%B6%E6%A1%B6/" rel="tag">Vue全家桶</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/js/" rel="tag">js</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/node/" rel="tag">node</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/Vue/" style="font-size: 20px;">Vue</a> <a href="/tags/Vue%E5%85%A8%E5%AE%B6%E6%A1%B6/" style="font-size: 10px;">Vue全家桶</a> <a href="/tags/js/" style="font-size: 15px;">js</a> <a href="/tags/node/" style="font-size: 10px;">node</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/07/">July 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/06/">June 2020</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2020/07/30/hello-world/">我的第一章博客</a>
          </li>
        
          <li>
            <a href="/2020/07/25/%E5%8E%9F%E7%94%9FHttp%E5%AE%9E%E7%8E%B0cookie%E8%AE%BE%E7%BD%AE/">原生Http实现cookie设置</a>
          </li>
        
          <li>
            <a href="/2020/07/23/%E5%B0%81%E8%A3%85Vue%E7%BB%84%E4%BB%B6%E5%B0%86%E4%BB%BB%E6%84%8F%E5%90%8E%E7%BC%80%E6%96%87%E4%BB%B6%E7%9B%AE%E5%BD%95%E7%BB%9F%E4%B8%80%E5%85%A8%E9%83%A8%E5%BC%95%E5%85%A5%E5%88%B0%E5%BD%93%E5%89%8D%E6%96%87%E4%BB%B6/">封装Vue组件将任意后缀文件目录统一全部引入到当前文件</a>
          </li>
        
          <li>
            <a href="/2020/07/15/js%E4%B8%AD%E7%9A%84%E9%98%B2%E6%8A%96%E4%B8%8E%E8%8A%82%E6%B5%81/">js中的防抖与节流</a>
          </li>
        
          <li>
            <a href="/2020/07/07/%E6%89%8B%E5%8A%A8%E5%AE%9E%E7%8E%B0call%EF%BC%8Capply,bind/">手动实现call，apply,bind</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2020 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css">

  
<script src="/fancybox/jquery.fancybox.pack.js"></script>




<script src="/js/script.js"></script>




  </div>
</body>
</html>